package com.apanal.qlife.common.shiro;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.util.StringUtils;

import com.apanal.qlife.common.factory.SpringContextHolder;
import com.apanal.qlife.sys.model.User;
import com.apanal.qlife.sys.service.UserService;

/**
 * shiro帮助类
 * 
 * 
 * @author shuliangxing
 * 
 * @date 2015-10-26上午11:44:50
 */
public class ShiroHelper {

	private static SessionDAO sessionDAO = SpringContextHolder
			.getBean("sessionDAO");

	private static UserService userService = SpringContextHolder
			.getBean("userServiceImpl");

	/**
	 * 根据Session获取登录用户身份(本系统是用户名)
	 * 
	 * @param session
	 * @return
	 */
	public static String getPrincipal(Session session) {
		if (session == null) {
			return null;
		}
		PrincipalCollection principalCollection = (PrincipalCollection) session
				.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		if (principalCollection == null) {
			return null;
		}
		return (String) principalCollection.getPrimaryPrincipal();
	}

	/**
	 * 根据用户身份获取session集合(用户重复登录等某些特定情况会出现多个session)
	 * 
	 * @param principal
	 * @return
	 */
	public static List<Session> getSession(String principal) {
		if (StringUtils.isEmpty(principal)) {
			return null;
		}
		List<Session> list = new ArrayList<Session>();
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		for (Session session : sessions) {
			if (session != null && principal.equals(getPrincipal(session))) {
				list.add(session);
			}
		}
		return list;
	}

	/**
	 * 根据机构id获取机构直属账号登录session集合
	 * 
	 * @param principal
	 * @return
	 */
	public static List<Session> getSession(Long orgId) {
		if (orgId == null) {
			return null;
		}
		List<Session> list = new ArrayList<Session>();
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		for (Session session : sessions) {
			if (session == null) {
				continue;
			}
			String username = getPrincipal(session);
			if (username == null) {
				continue;
			}
			User user = userService.findByUsername(username);
			if (orgId.equals(user.getOrgId())) {
				list.add(session);
			}
		}
		return list;
	}
}
